<template>
  <!-- 首页 -->
  <div class="home">
    <van-nav-bar>
      <template #right>
        <van-button
          style="height: 60%;"
          round
          color="#5aabfb"
          icon="search"
          @click="$router.push('/search')">
          搜索
        </van-button>
      </template>
    </van-nav-bar>
    <div class="content">
      <van-tabs v-model="active" @change="tabChange">
        <van-tab v-for="(i, index) in list" :key="i.id" :title="i.name">
          <ArtList :index="index" :artId="i.id" :ref="'art_' + index"></ArtList>
        </van-tab>
      </van-tabs>
      <van-icon name="wap-nav" @click="showChannel" />
    </div>
    <ChannelEdit
      ref="channelEdit"
      :list="list"
      v-model="active"
      @setList="setList"
    />
  </div>
</template>
<script>
import { userChannels, userChannelsPut } from '@/api/home'
import ArtList from './components/artList.vue'
import ChannelEdit from './components/channelEdit.vue'
export default {
  name: 'Home',
  components: {
    ArtList,
    ChannelEdit
  },
  data () {
    return {
      active: 0,
      list: []
    }
  },
  created () {
    this.getData()
  },
  activated () {
  },
  methods: {
    async getData () {
      if (this.$store.state.tokenObj.token || !localStorage.getItem('list')) {
        const res = await userChannels()
        this.list = res.data.data.channels
      } else {
        if (localStorage.getItem('list')) {
          this.list = JSON.parse(localStorage.getItem('list'))
        } else {
          const res = await userChannels()
          this.list = res.data.data.channels
        }
      }
    },
    tabChange () {
      this.$nextTick(() => {
        this.$refs['art_' + this.active][0].backScrollTop()
      })
    },
    showChannel () {
      this.$refs.channelEdit.isShow = true
    },
    async setList ({ method, value }) {
      if (method === 'push') {
        this.list.push(value)
      } else if (method === 'splice') {
        this.list.splice(value, 1)
      }
      localStorage.setItem('list', JSON.stringify(this.list))
      if (this.$store.state.tokenObj.token) {
        const channels = this.list.map((item, index) => {
          return {
            id: item.id,
            seq: index
          }
        })
        await userChannelsPut({
          channels: channels
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
.content {
  position: relative;
  .van-icon {
    position: absolute;
    top: 8px;
    right: 0;
    font-size: 26px;
  }
  .van-tabs {
    padding-right: 30px;
  }
}
</style>
